import db from './db';
import { userInfo } from '../models/apis/userInfo';

export default class current {
  private static _instance: current = null;

  public static get instance(): current {
    if (this._instance == null)
      this._instance = new current();
    return this._instance;
  }

  private constructor() {
    this.loadInfo();
  }

  private _mid: string = '';

  public get mid() {
    return this._mid;
  }

  private _token: string = '';

  public get token() {
    return this._token;
  }

  private _info: userInfo;

  public get info() {
    return this._info;
  }

  public loadInfo(): Promise<void> {
    return new Promise((resolve) => {
      db.instance.query('mid').then((value) => {
        this._mid = value.toString();
      });
      db.instance.query('token').then((value) => {
        this._token = value.toString();
      });
      db.instance.query('info').then((value) => {
        let info: userInfo = JSON.parse(value.toString());
        this._info = info;
      });
      resolve();
    });
  }

  public clear() {
    this._mid = '';
    this._token = '';
    this._info = null;
    db.instance.update('mid', '');
    db.instance.update('info', '');
    db.instance.update('token', '');
  }
}